#include "sqliteDataBase.h"

SqliteDataBase::SqliteDataBase() : m_db(NULL)
{
}

SqliteDataBase::~SqliteDataBase()
{
}

/* 连接数据库 */
bool SqliteDataBase::connectDB(const std::string &connStr)
{
    int ret = sqlite3_open(connStr.c_str(), &m_db);
    if (ret != SQLITE_OK)
    {
        std::cerr << "sqlite3 open error. " << std::endl;
        exit(-1);
    }
    return true;
}

/* 执行Sql语句(exec) */
bool SqliteDataBase::executeSql(const std::string &sql)
{
    int ret = sqlite3_exec(m_db, sql.c_str(), NULL, NULL, NULL);
    if (ret != SQLITE_OK)
    {
        std::cerr << "exec error: " << std::endl;
        return false;
    }
    return true;
}

/* 查询Sql语句(select) */
QueryResult SqliteDataBase::querySql(const std::string &sql)
{
    char **result = NULL;
    int rows, columns = 0;
    QueryResult res;

    int ret = sqlite3_get_table(m_db, sql.c_str(), &result, &rows, &columns, NULL);
    if (ret != SQLITE_OK)
    {
        std::cout << "sqlite3 get table error." << std::endl;
        return res;
    }

    /* 列名 */
    for (int idx = 0; idx < columns; idx++)
    {
        res.columnName.push_back(result[idx]);
    }

    for (int row = 1; row <= rows; row++)
    {
        std::vector<std::string> tmp;

        for (int col = 0; col < columns; col++)
        {
            tmp.push_back(result[row * columns + col]);
        }
        res.rows.push_back(tmp);
    }
    return res;
}
/* 关闭数据库连接 */
void SqliteDataBase::close()
{
    /* 关闭数据库 */
    sqlite3_close(m_db);
}
